package com.example.myys.ui.page.xsPage

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myys.common.TopItem
import com.example.myys.data.entity.DataBean
import com.example.myys.ui.Resource
import com.example.myys.ui.StateHandler
import com.example.myys.ui.base.DialogWithImage
import com.example.myys.ui.base.ListItem
import com.example.myys.ui.base.PickSth
import com.example.myys.ui.base.SearchBar
import com.example.myys.viewModel.xsModel.XsSjViewModel

//顶部导航栏数据定义
object PagesXs {
    const val SJ = "Sj" //书架
    const val SC = "Sc" //书城
    const val SJNR="Sjnr" //书籍内容
}
//小说展示
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Xs(navController: NavController, modifier: Modifier) {
    val xsViewModel: XsSjViewModel = viewModel()
    val scTjState by xsViewModel.scTjState.collectAsState()
    val sjState by xsViewModel.sjState.collectAsState()

    //滑动导航
    val dataBar = listOf(
        TopItem(PagesXs.SJ, "书架"),
        TopItem(PagesXs.SC, "书城"),
    )
    var state by remember { mutableStateOf(0) }
    val scope= rememberCoroutineScope()

    Column {
        ScrollableTabRow(selectedTabIndex = state) {
            dataBar.forEachIndexed { index, item ->
                Tab(text = {
                    Text(text = item.label)
                }, selected = state == index, onClick = {
                    state = index
                })
            }
        }

        when (state) {
                0->XsSj(sjState,navController,xsViewModel)
                1-> XsSc(scTjState = scTjState, navController = navController, marsViewModel =xsViewModel )
            }

    }
}
//小说书架
@Composable
fun XsSj(sjState:Resource<List<DataBean>>,navController: NavController,marsViewModel:XsSjViewModel) {
    Scaffold(floatingActionButton = {
        FloatingActionButton(onClick = { /*TODO*/ }) {
            PickSth{filePath,fileName->
                Log.d("[TestPick]", "picked a file ${fileName}. path:${filePath.toString()}")
            }
        }
    },
        floatingActionButtonPosition = FabPosition.End
    ) { padding->
        StateHandler(state = sjState) {resource ->resource.data?.let { sjList->
            LazyVerticalGrid(
                columns = GridCells.Adaptive(minSize = 300.dp),
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
                modifier = Modifier.padding(padding)
            ) {
                    items(sjList) { xsItem ->
                        ItemContenXs(
                            itemData = xsItem,
                            navController = navController,
                            marsViewModel
                        )
                    }

            }
        }
        }
    }
}
@Composable
fun XsSc(scTjState: Resource<List<DataBean>>,navController: NavController,marsViewModel: XsSjViewModel){
    Column {
        SearchBar(onSearchClick = {
            marsViewModel.getSearchBook(it)
        })
        StateHandler(state = scTjState) {resource ->resource.data?.let { scList->
            ResultScreen(
                scList, navController = navController,marsViewModel
            )
        }}
    }
}

//小说书城成功页
@Composable
fun ResultScreen(xsListData:List<DataBean>, navController: NavController,marsViewModel:XsSjViewModel) {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 300.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        xsListData?.let {
            items(it) { xsItem ->
                ItemXs(itemData = xsItem, navController = navController,
                    saveBookSelf = {
                    marsViewModel.addBookShelf(xsItem)
                    }
                )
            }
        }
        item {
            Text(text = "无更多数据")
        }
    }
    /*FlowRow (modifier = Modifier.verticalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(20.dp)){
        xsListData.forEach{xsItem->
            ItemXs(itemData = xsItem,navController=navController)
        }
    }*/
}
//书城展示列表项
@Composable
fun ItemXs(itemData: DataBean, navController: NavController,saveBookSelf:()->Unit) {
    // 获取 context
    val context = LocalContext.current
    //详情弹窗
    var dialogShow by remember {
        mutableStateOf(false)
    }
    ListItem(onClickItem = {dataBean ->
        Toast.makeText(context, "链接:" + dataBean.url, Toast.LENGTH_LONG)
            .show()
        dialogShow=true
    }, dataBean = itemData)
    if (dialogShow){
        DialogWithImage(onDismissRequest = {dialogShow=false},
            onPlay = {navController.navigate("${PagesXs.SJNR}?url=${itemData.url}&dataId=${itemData.id}")},
            onConfirmation = {
                saveBookSelf()
                Toast.makeText(context, "加入书架成功", Toast.LENGTH_SHORT).show()
                dialogShow=false},
            itemData
        )
    }
}
//书架展示列表项
@Composable
fun ItemContenXs(itemData: DataBean, navController: NavController, marsViewModel: XsSjViewModel) {
    // 获取 context
    val context = LocalContext.current
    ListItem(onClickItem = {
        Toast.makeText(context, "链接:" + it.url, Toast.LENGTH_LONG)
            .show()
        navController.navigate("${PagesXs.SJNR}?url=${it.url}&dataId=${it.id}")
    }, dataBean = itemData,
        onDeleteClick = {
            marsViewModel.deleteBookShelf(it)
        }, isDeleteAble = true
    )
}
